package web.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rdc.example.bean.Result;
import com.rdc.example.bean.dto.UserDTO;
import com.rdc.example.service.FollowService;
import com.rdc.example.service.impl.FollowServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/follow/*")
@MultipartConfig
public class FollowServlet extends BaseServlet {

    FollowService followService = new FollowServiceImpl();

    public void turnFollow(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //前端获取被关注id
        Integer followedId = Integer.valueOf(req.getParameter("followedId"));
        //在session中获取关注者id
        HttpSession session = req.getSession();
        Integer followerId=((UserDTO) session.getAttribute("userDTO")).getId();
        //获取关注状态反转结果
        Result result = followService.turnFollow(followerId,followedId);
        System.out.println(result);
        //json发送
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSONObject.toJSONString(result));
    }

    public void checkFollow(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //前端获取被关注id
        Integer followedId = Integer.valueOf(req.getParameter("followedId"));
        //在session中获取关注者id
        HttpSession session = req.getSession();
        Integer followerId=((UserDTO) session.getAttribute("userDTO")).getId();
        //获取关注状态反转结果
        boolean status= followService.check(followerId,followedId);
        //json发送
        //如果关注了，就是true, 没关注就是false
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSONObject.toJSONString(status));
    }

    public void batchCheck(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject params = JSON.parseObject(req.getParameter("data"));
        List<Integer> userIds = params.getJSONArray("userIds").toJavaList(Integer.class);
        //在session中获取关注者id
        HttpSession session = req.getSession();
        Integer followerId = ((UserDTO) session.getAttribute("userDTO")).getId();
        //批量获取关注状态结果
        Map<Integer, Boolean> statusMap = followService.batchCheck(followerId, userIds);
        //json发送
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSONObject.toJSONString(statusMap));
    }

}
